import time
import re
import json
import urllib
import scrapy
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
import math
import requests
import base64
from urllib.parse import urlencode


class spider(BaseTaxPolicySpider):
    name = "sichuan_bzsbzqrmzfqzfbgswj"

    province: str = "四川省"  # 取表格
    city: str = "巴中市"  # 取表格
    county: str = "巴州区"  # 取表格
    park: str = "None"  # 取表格
    source: str = "巴中市巴州区人民政府"  # 取表格 同一个来源合并
    url: str = "http://www.bzqzf.gov.cn/public/column/6597391?type=4&action=list&nav=2&sub=2&catId=6716381"  # 注明入口网址，以便后续排错
    headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
        'Pragma': 'no-cache',
        'Sec-Fetch-Dest': 'document',
        'Sec-Fetch-Mode': 'navigate',
        'Sec-Fetch-Site': 'none',
        'Sec-Fetch-User': '?1',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36',
        'sec-ch-ua': '"Not A(Brand";v="8", "Chromium";v="132", "Google Chrome";v="132"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"'
    }

    def start_requests(self):
        url = "http://www.bzqzf.gov.cn/public/column/6597391?type=4&action=list&nav=2&sub=2&catId=6716381"

        # 发送GET请求
        yield scrapy.Request(url=url, method='GET', headers=self.headers, callback=self.detail_requests)

    def detail_requests(self, response, **kwargs):
        page = response.meta.get('page', "")
        links = response.xpath("//div[@class='xxgk_navli']//div[@class='nr']/a/@href").getall()  # 取链接
        title_list = response.xpath("//div[@class='xxgk_navli']//div[@class='nr']/a/text()").getall()  # 取链接
        pubdate_lsit = response.xpath("//div[@class='xxgk_navli']//li[@class='rq']/text()").getall()  # 取链接
        print("links", len(links), links)
        print("title_list", len(title_list), title_list)
        if len(title_list) == len(links):
            for i in range(len(links)):
                if 'http' not in links[i]:
                    # if links[i].count('.') == 1:
                    #     links[i] = f"http://www.shimian.gov.cn{links[i]}"
                    if links[i].count('.') == 5:
                        links[i] = f"http://www.hanyuan.gov.cn{links[i][5:]}"
                    if links[i].count('.') == 7:
                        links[i] = f"http://www.hanyuan.gov.cn{links[i][8:]}"
                    if links[i].count('.') == 9:
                        links[i] = f"https://www.scqs.gov.cn{links[i][11:]}"
                print("links[i]", links[i], 'page', page)
                yield scrapy.Request(links[i], headers=self.headers, callback=self.parse_list,
                                     meta={'is_next': False, 'page': page, 'title': title_list[i],
                                           })
        else:
            raise ValueError("数量错误", page, len(title_list), len(pubdate_lsit), len(title_list), response.text)
        # 翻页逻辑
        if response.meta.get("is_next") is not False:
            match = re.search(r'pageCount\s*:\s*([^,\}\s]+)', response.text)
            if match:
                result = match.group(1)
                print("总页数：", result)
                for page in range(2, int(result) + 1):
                    print("当前页：", page)
                    next_page = f"http://www.bzqzf.gov.cn/site/label/8888?IsAjax=1&dataType=html&_=0.32774841581119496&labelName=publicInfoList&siteId=6787291&pageSize=18&pageIndex={page}&action=list&isDate=true&dateFormat=yyyy-MM-dd&length=50&organId=6597391&type=4&catId=6716381&cId=&result=%E6%9A%82%E6%97%A0%E7%9B%B8%E5%85%B3%E4%BF%A1%E6%81%AF&file=%2Fc2%2Fbazhou%2FpublicInfoList_new"
                    yield scrapy.Request(url=next_page, method='GET', headers=self.headers,
                                         callback=self.detail_requests, meta={'is_next': False, 'page': page})
            else:
                raise ValueError("找不到下一页")

    def parse_list(self, response, **kwargs):
        if "正在跳转到" in response.text:
            # raise ValueError("需要跳转")
            change_url = re.search(r'location\.href\s*=\s*["\'](http[^"\']+)["\']', response.text).group(1)
            print(response.url, "---", change_url)
            yield scrapy.Request(change_url, headers=self.headers, callback=self.parse_detail,
                                 meta={'is_next': False, 'title': response.meta.get('title'),
                                       'pubdate': response.meta.get('pubdate')})
        else:
            item = Item()
            if 'pdf' in response.url or 'doc' in response.url or 'xls' in response.url or 'jpg' in response.url:
                print("特殊url：", response.url)
                content = response.url

            else:
                content = response.xpath(".").get()
            item['title'] = response.xpath("//title/text()").get()
            item['source_url'] = response.url
            item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
            item['content'] = content
            item['source'] = self.source
            item['province'] = self.province
            item['city'] = self.city
            item['county'] = self.county
            item['park'] = self.park
            if self.insert:
                yield item
            else:
                print("item", item)

    def parse_detail(self, response, **kwargs):
        item = Item()
        if 'pdf' in response.url or 'doc' in response.url or 'xls' in response.url or 'jpg' in response.url:
            print("特殊url：", response.url)
            content = response.url

        else:
            content = response.xpath(".").get()
        item['title'] = response.xpath("//title/text()").get().replace(" ", "").replace("\r\n", "")
        item['source_url'] = response.url
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = content
        item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        if self.insert:
            yield item
        else:
            print("item", item)

    # insert: str = False
    insert: str = True


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl sichuan_bzsbzqrmzfqzfbgswj".split())
